<?php

namespace app\store\controller\market;

use app\store\controller\BaseController;
use app\store\model\Task;
use app\store\service\ComboService;
use app\store\service\TaskService;
use think\exception\ValidateException;
use think\facade\View;

class TaskController extends BaseController
{
    public function index()
    {
        $param = $this->request->param();

        $list = TaskService::getTaskList($param);

        return View::fetch('',['list' => $list]);
    }

    public function create()
    {
        $comboOptions = ComboService::getComboOptions();

        return View::fetch('',['comboOptions' => $comboOptions]);
    }

    public function edit()
    {
        $id = $this->request->param('id/d');

        $comboOptions = ComboService::getComboOptions();
        $row = TaskService::findTask($id);

        return View::fetch('',['comboOptions' => $comboOptions, 'row' => $row]);
    }

    public function save()
    {
        $param = $this->request->param();

        try {
            validate('TaskValidate')->check($param);
        }catch (ValidateException $e){
            return json(['code' =>0, 'msg' => $e->getMessage()]);
        }
        $param['store_id'] = session('store_id');
        $task = Task::create($param);

        return $task['id'] ? json(['code' =>1, 'msg' => '保存成功!']) : json(['code' =>0, 'msg' => '保存失败!']);
    }


    public function update()
    {
        $param = $this->request->param();

        try {
            validate('TaskValidate.edit')->check($param);
        }catch (ValidateException $e){
            return json(['code' =>0, 'msg' => $e->getMessage()]);
        }
        $task = Task::update($param);

        return $task['id'] ? json(['code' =>1, 'msg' => '更新成功!']) : json(['code' =>0, 'msg' => '更新失败!']);
    }

    public function delete()
    {
        $id = $this->request->param('id/d');
        $res = Task::destroy($id);

        return $res ? json(['code' =>1, 'msg' => '删除成功!']) : json(['code' =>0, 'msg' => '删除失败!']);
    }
}